package base

import (
	"bytes"
	"context"
	"fmt"
	"github.com/bytedance/sonic"
	"github.com/zeromicro/go-zero/core/logc"
	"io"
	"net/http"
)

type Config struct {
	MappingCode string
	Url         string
	SecretKey   string
	MerchantId  string
	PrivateKey  string
	AppId       string
	ReturnUrl   string
	NotifyUrl   string
	AppCode     string
}

type WithdrawRes struct {
	OrderSn      string `json:"order_sn"`
	ThirdOrderSn string `json:"third_order_sn"`
}

type Payment interface {
	// Withdraw 提现/代付接口
	Withdraw(ctx context.Context, params map[string]any) (WithdrawRes, error)
}

// SendJson 发送三方 http 请求 application/json 方式
func SendJson(ctx context.Context, url string, data map[string]interface{}, method string) (string, error) {
	// Convert data to JSON
	jsonData, err := sonic.Marshal(data)
	if err != nil {
		return "", err
	}
	// Create a new HTTP request
	m := http.MethodPost
	if method == "get" {
		m = http.MethodGet
	}
	req, err := http.NewRequest(m, url, bytes.NewBuffer(jsonData))
	if err != nil {
		return "", err
	}

	// Set the appropriate headers
	req.Header.Set("Content-Type", "application/json")

	// Create a new HTTP client and send the request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// Read the response body
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	resStr := string(body)

	// Log the request and response
	fmt.Printf("URL: %s\nData: %s\nResponse: %s\n", url, string(jsonData), resStr)
	logc.Info(ctx, "url", url, "request", string(jsonData), "response", resStr)

	return resStr, nil
}
